package com.connor.bank.Entity;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Login {

    private String username;
    private String password;
    private final String ALGORITHM = "MD5";

    public Login(String username, String password) {
        try {
            this.username = username;
            MessageDigest md = MessageDigest.getInstance(ALGORITHM);
            md.update(password.getBytes());
            BigInteger hash = new BigInteger(1, md.digest());
            this.password = hash.toString(16);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String getUsername() {
        return username;
    }

    public boolean validate() {
        String sql = String.format("Select * from LOGIN where username=\"%s\" and password = \"%s\"", username, password);
        DatabaseConnection dbc = null;
        try {
            dbc = new DatabaseConnection();
            ResultSet rs = dbc.executeQuery(sql);
            return rs.next();
        } catch (SQLException ex) {
            // TODO Auto-generated catch block
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } finally {
            if (dbc != null) {
                dbc.closeConnection();
            }
        }
    }
}
